<?php

namespace app\api\controller\kuyou\applet;

use app\common\model\Attachment;
use app\api\model\kuyou\applet\Goods as Goodss;
use app\api\model\kuyou\applet\Sets;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Shared\Date as PHPExcel_Shared_Date;
use think\Db;
use think\Session;

/**
 * 商品接口
 */
class Goods extends Common
{
    protected $noNeedRight = ['getDetail','getgoodsprice','getgoodsunit','getgoodswaring','getgoodsauxiliary','getauxiliary','getgoodsbatch','getgoodsperiod','editdetails','getgoodsinfo','choseGoods','formatInfo','auxiliary','getCostPrice','getgoodsinfo_c','getLastUser','getGoods','getgoodslist'];

    /**
     * 获取商品
     * @ApiMethod (POST)
     * @param int $page 页码
     * @param int $limit 每页条数
     * @param string $name 商品名称
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $page = $this->request->post('page');
            $page = empty($page)?1:$page;
            $limit = $this->request->post('limit');
            $limit = empty($limit)?config('app_limit'):$limit;

            $where = [];
            $keyword = $this->request->post('keyword');
            if(!empty($keyword)){
                $where['goods_code|goods_name|goods_barcode|goods_specification_id'] = ['like','%'.$keyword.'%'];
            }else{
                $code = $this->request->post('goods_code');
                if(!empty($code)){
                    $where['goods_code'] = ['like','%'.$code.'%'];
                }
                $name = $this->request->post('goods_name');
                if(!empty($name)){
                    $where['goods_name'] = ['like','%'.$name.'%'];
                }
                $barcode = $this->request->post('goods_barcode');
                if(!empty($barcode)){
                    $where['goods_barcode'] = ['like','%'.$barcode.'%'];
                }
                $goods_spec = $this->request->post('goods_spec');
                if(!empty($goods_spec)){
                    $where['goods_specification_id'] = ['like','%'.$goods_spec.'%'];
                }
            }
            $goods_type_id = $this->request->post('goods_type_id');
            if(!empty($goods_type_id)){
                $where['goods_type_id'] = $goods_type_id;
            }
            $status = $this->request->post('status');
            if($status!=null && $status!==''){
                $where['status'] = $status;
            }

            $result = Goodss::getList($where,$page,$limit);

            if(isset($result['list']) && isset($result['count'])){
                $this->success('查询成功',$result,200);
            }else{
                $this->error('查询失败','',406);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取商品详情
     * @ApiMethod (POST)
     * @param int $id 商品ID
     */
    public function getdetail()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $type = $this->request->post('type');
            $type = empty($type)?0:1;
            if(empty($id)){
                $this->error('请输入查询参数','',500);
            }
            $result = Goodss::getDetail($id,$type);
            if($result['status']==200){
                $this->success('查询成功',$result['msg'],200);
            }else{
                $this->error($result['msg'],'',$result['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取商品价格策略
     * @ApiMethod (POST)
     * @param int $id 商品ID
     */
    public function getgoodsprice()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $goods = (new \app\api\model\kuyou\applet\Goods())->where(['id'=>$id])->value('id');
            if(empty($goods)){
                $this->error('未查询到相关商品','',500);
            }
            $result = Goodss::getGoodsPrice($id);
            $this->success('查询成功',$result,200);
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取商品多单位以及单位价格
     * @ApiMethod (POST)
     * @param int $id 商品ID
     */
    public function getgoodsunit()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $goods = (new \app\api\model\kuyou\applet\Goods())->where(['id'=>$id])->value('id');
            if(empty($goods)){
                $this->error('未查询到相关商品','',500);
            }
            $result = Goodss::getGoodsUnit($id);
            $this->success('查询成功',$result,200);
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取商品库存预警信息
     * @ApiMethod (POST)
     * @param int $id 商品ID
     */
    public function getgoodswaring()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $goods = (new \app\api\model\kuyou\applet\Goods())->where(['id'=>$id])->value('id');
            if(empty($goods)){
                $this->error('未查询到相关商品','',500);
            }
            $result = Goodss::getGoodsWaring($id);
            $this->success('查询成功',$result,200);
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取商品属性信息
     * @ApiMethod (POST)
     * @param int $id 商品ID
     */
    public function getgoodsauxiliary()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $goods = (new \app\api\model\kuyou\applet\Goods())->where(['id'=>$id])->value('id');
            if(empty($goods)){
                $this->error('未查询到相关商品','',500);
            }
            $result = Goodss::getGoodsAuxiliary($id);
            $this->success('查询成功',$result,200);
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取商品属性组合
     * @ApiMethod (POST)
     * @param string $aid 一级属性ID
     * @param string $aids 二级属性ID
     */
    public function getauxiliary()
    {
        if ($this->request->isPost()) {
            $aid = $this->request->post('aid');
            $aid = explode(',',$aid);
            $aids = $this->request->post('aids');
            $aids = explode(',',$aids);
            $result = Goodss::auxiliary($aid,$aids);
            $this->success('查询成功',$result,200);
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取商品批次保质期信息
     * @ApiMethod (POST)
     * @param int $id 商品ID
     */
    public function getgoodsbatch()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $goods = (new \app\api\model\kuyou\applet\Goods())->where(['id'=>$id])->value('id');
            if(empty($goods)){
                $this->error('未查询到相关商品','',500);
            }
            $result = Goodss::getGoodsBatch($id);
            $this->success('查询成功',$result,200);
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取商品期初信息
     * @ApiMethod (POST)
     * @param int $id 商品ID
     */
    public function getgoodsperiod()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $goods = (new \app\api\model\kuyou\applet\Goods())->where(['id'=>$id])->value('id');
            if(empty($goods)){
                $this->error('未查询到相关商品','',500);
            }
            $result = Goodss::getGoodsPeriod($id);
            $this->success('查询成功',$result,200);
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 添加商品
     * @ApiMethod (POST)
     * @param array $detail 商品数据
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            foreach ($data as $k=>$v){
                $data[$k] = is_array($v)?$v:html_entity_decode($v);
            }
            $ret = Goodss::addDetail($data);
            if($ret['status']==200){
                $this->success('添加成功',$ret['msg'],200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 更新商品
     * @ApiMethod (POST)
     * @param array $detail 商品数据
     */
    public function edit()
    {
        if ($this->request->isPost()) {
                $data = $this->request->post();
                foreach ($data as $k=>$v){
                    $data[$k] = is_array($v)?$v:html_entity_decode($v);
                }
                $ret = Goodss::editDetail($data);
                if($ret['status']==200){
                    $this->success('更新成功','',200);
                }else{
                    $this->error($ret['msg'],'',$ret['status']);
                }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 批量更新商品
     * @ApiMethod (POST)
     * @param array $detail 商品数据
     */
    public function editdetails()
    {
        if ($this->request->isPost()) {
                $data = $this->request->post();
                foreach ($data as $k=>$v){
                    $data[$k] = is_array($v)?$v:html_entity_decode($v);
                }
                $ret = Goodss::editDetails($data);
                if($ret['status']==200){
                    $this->success('更新成功','',200);
                }else{
                    $this->error($ret['msg'],'',$ret['status']);
                }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 删除商品
     * @ApiMethod (POST)
     * @param int $id 商品id
     */
    public function del()
    {
        if ($this->request->isPost()) {
                $id = $this->request->post('id');
                $ret = Goodss::delDetail($id);
                if($ret['status']==200){
                    $this->success('删除成功',$ret['msg'],200);
                }else{
                    $this->error($ret['msg'],'',$ret['status']);
                }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 导入商品
     * @ApiMethod (POST)
     * @param string $file 商品文件路径（先上传文件后直接传入文件路径）
     */
    public function import()
    {
        if ($this->request->isPost()) {
            $file = $this->request->post('file');
            $type = $this->request->post('type');
            if(empty($file)){
                $this->error('请选择上传文件','',500);
            }

            $set_time = (new Sets())::getSet('enable_time');
            $set_time = isset($set_time[0]['value'])?strtotime($set_time[0]['value']):time();

            $filePath = ROOT_PATH . 'public' . $file;
            $filePath = str_replace("\\",'/',$filePath);
            if (!is_file($filePath)) {
                $this->error('未找到上传文件，请重新上传','',500);
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error('文件格式错误，请重新上传','',500);
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);
                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error('读取文件失败，请重新上传','',500);
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

                $titles = [];
                for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $titles[] = $val;
                    }
                }

                $fields = [];
                for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $val = str_replace('*','',$val);
                        $fields[] = (string)$val;
                    }
                }
                if(!in_array('商品类别',$fields)
                    || !in_array('商品编号',$fields)
                    || !in_array('商品名称',$fields)
                    || !in_array('规格型号',$fields)
                    || !in_array('首选仓库',$fields)
                    || !in_array('计量单位',$fields)
                    || !in_array('换算率',$fields)
                    || !in_array('备注',$fields)
                    || !in_array('商品/属性条码',$fields)
                    || !in_array('预计采购价',$fields)
                    || !in_array('零售价',$fields)
                    || !in_array('批发价',$fields)
                    || !in_array('会员价',$fields)
                    || !in_array('折扣率一',$fields)
                    || !in_array('折扣率二',$fields)
                ){
                    exception('数据格式错误，请重新上传');
                }

                foreach ($fields as $fields_k=>$fields_v){
                    if($fields_v=='期初数量'){
                        $fields[$fields_k] = '期初数量-'.(isset($titles[$fields_k])?$titles[$fields_k]:'');
                    }
                    if($fields_v=='单位成本'){
                        $fields[$fields_k] = '单位成本-'.(isset($titles[$fields_k-1])?$titles[$fields_k-1]:'');
                    }
                }

                for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = array_combine($fields, $values);
                    $insert[] = $row;
                }
            } catch (Exception $exception) {
                $this->error($exception->getMessage(),'',500);
            }
            if (!$insert) {
                $this->error('未读取到有效数据，请重新上传','',500);
            }

            //检验商品编号是否重复,是否合法
            $code = [];
            foreach ($insert as $insert_k=>$insert_v){
                if(!empty($insert_v['商品编号']) && !empty($insert_v['商品名称'])){
                    if(!in_array($insert_v['商品编号'],$code)){
                        $code[] = $insert_v['商品编号'];
                    }else{
                        $this->error('导入失败，编号'.$insert_v['商品编号'].'重复','',500);
                    }
                    $status = checkCode($insert_v['商品编号'],6);//验证编号是否合法
                    if(!$status){
                        $this->error('导入失败，编号'.$insert_v['商品编号'].'不合法','',500);
                    }
                }
            }

            $sku = $this->request->post('sku');
            $sku = explode(',',$sku);
            $sku = empty($sku)?[]:$sku;
            if(!empty($sku)){
                $auxiliary = (new \app\api\model\kuyou\applet\Auxiliary())->where(['id'=>['in',$sku]])->column('id','name');
                if(sizeof($auxiliary) != sizeof($sku)){
                    $this->error('商品属性查询错误，导入失败');
                }
                foreach ($auxiliary as $auxiliary_k=>$auxiliary_v){
                    if(isset($row[$auxiliary_k])){
                        $attr[] = $auxiliary_k;
                    }else{
                        $this->error('请输入属性‘'.$auxiliary_k.'’信息');
                    }
                }
            }
            if(!empty($attr)){
                $auxiliary = (new \app\api\model\kuyou\applet\Auxiliary())->where(['name'=>['in',$attr]])->column('id','name');
                if(sizeof($attr)!=sizeof($auxiliary)){
                    foreach ($attr as $attr_k=>$attr_v){
                        if(!isset($auxiliary[$attr_v])){
                            $this->error('辅助属性'.$attr_v.'不存在');
                        }
                    }
                }
                $attr_arr = [];
                foreach ($attr as $attr_k=>$attr_v){
                    foreach ($insert as $insert_k=>$insert_v){
                        if(!empty($insert_v[$attr_v]) && !in_array($insert_v[$attr_v],$attr_arr)){
                            $attr_arr[] = $insert_v[$attr_v];
                        }
                        if(!isset($insert[$insert_k]['auxiliary_type'])){
                            $insert[$insert_k]['auxiliary_type'] = [];
                        }
                        if(!empty($insert_v[$attr_v]) && !in_array($insert_v[$attr_v],$insert[$insert_k]['auxiliary_type'])){
                            $insert[$insert_k]['auxiliary_type'][] = $auxiliary[$attr_v];
                        }
                        $insert[$insert_k]['attr_arr'] = [];
                    }
                }
                if(!empty($attr_arr)){
                    $auxiliary = (new \app\api\model\kuyou\applet\Auxiliary())->where(['name'=>['in',$attr_arr]])->column('id','name');
                    if(sizeof($attr_arr)!=sizeof($auxiliary)){
                        foreach ($attr_arr as $attr_arr_k=>$attr_arr_v){
                            if(!isset($auxiliary[$attr_arr_v])){
                                $this->error('属性'.$attr_arr_v.'不存在');
                            }
                        }
                    }
                    foreach ($attr as $attr_k=>$attr_v){
                        foreach ($insert as $insert_k=>$insert_v){
                            if(!empty($insert_v[$attr_v])){
                                $insert[$insert_k]['attr_arr'][] = $auxiliary[$insert_v[$attr_v]];
                            }
                        }
                    }
                }
            }

            foreach ($insert as $insert_k=>$insert_v){
                if(!empty($insert_v['auxiliary_type'])){
                    $insert[$insert_k]['auxiliary_type'] = serialize($insert_v['auxiliary_type']);
                    $insert[$insert_k]['auxiliary_type_c'] = serialize($insert_v['attr_arr']);
                    $insert[$insert_k]['auxiliary'] = 1;
                }else{
                    $insert[$insert_k]['auxiliary_type'] = '';
                    $insert[$insert_k]['auxiliary_type_c'] = '';
                    $insert[$insert_k]['auxiliary'] = 0;
                }
                if(isset($insert_v['attr_arr']) && !empty($insert_v['attr_arr'])){
                    $attr_arr = $insert_v['attr_arr'];
                    asort($attr_arr);
                    $attr_arr = implode('&',$attr_arr);
                    $attr_id = Db::name('kuyou_aux_combination')->where(['attr_ids'=>$attr_arr,'attr_code'=>$insert_v['属性编号']])->value('id');
                    if($attr_id){
                        $insert[$insert_k]['attr_arr'] = $attr_id;
                    }else{
                        $insert[$insert_k]['attr_arr'] = Db::name('kuyou_aux_combination')->insertGetId([
                            'attr_ids'=>$attr_arr,
                            'attr_code'=>$insert_v['属性编号'],
                            'createtime'=>time(),
                            'updatetime'=>time(),
                        ]);
                    }
                }else{
                    $insert[$insert_k]['attr_arr'] = '';
                }
            }


            //分类数据
            $cate = [];
            $catedata = [];
            //计量单位
            $unit = [];
            $unit_con = [];
            //商品编号
            $goods_code = [];
            //仓库
            $stores = [];
            $attr = [];
            $row = $insert[0];
            foreach ($insert as $insert_k=>$insert_v){
                //商品编号
                if(!empty($insert_v['商品编号'])){
                    if(!in_array($insert_v['商品编号'],$goods_code)){
                        $goods_code[] = $insert_v['商品编号'];
                    }
                }
                if(!empty($insert_v['首选仓库'])){
                    if(!in_array($insert_v['首选仓库'],$stores)){
                        $stores[] = $insert_v['首选仓库'];
                    }
                }
                //分类数据
                if(empty($insert_v['商品编号']) && empty($insert_v['商品/属性条码'])){
                    unset($insert[$insert_k]);
                }else{
                    if(!empty($insert_v['商品类别'])){
                        $nowcate = trim($insert_v['商品类别']);
                        $catedata[] = $nowcate;
                        if(strpos($nowcate,'/') !== false){
                            $caterow = explode('/',$nowcate);
                            foreach ($caterow as $caterow_k=>$caterow_v){
                                if(!in_array($caterow_v,$cate) && !empty($caterow_v)){
                                    $cate[] = $caterow_v;
                                }
                            }
                        }else{
                            if(!in_array($nowcate,$cate) && !empty($nowcate)){
                                $cate[] = $nowcate;
                            }
                        }
                    }
                }
                //计量单位
                if(!empty($insert_v['计量单位'])){
                    $nowunit = trim($insert_v['计量单位']);
                    if(strpos($nowunit,'/') !== false){
                        if(empty($insert_v['换算率'])){
                            $this->error('多计量单位的换算率必填');
                        }
                        $unitrow = explode('/',$nowunit);
                        $advance_rate = explode('/',trim($insert_v['换算率']));
                        if(sizeof($unitrow)!=sizeof($advance_rate)){
                            $this->error('多计量单位的换算率与计量单位不匹配');
                        }
                        $unit_con[] = [
                            'unit'=>$nowunit,
                            'advance_rate'=>trim($insert_v['换算率']),
                        ];
                        foreach ($unitrow as $unitrow_k=>$unitrow_v){
                            if(!in_array($unitrow_v,$unit) && !empty($unitrow_v)){
                                $unit[] = $unitrow_v;
                            }
                        }
                    }else{
                        if(!in_array($nowunit,$unit) && !empty($nowunit)){
                            $unit[] = $nowunit;
                        }
                    }
                }
            }
            $catelist = Db::name('kuyou_goods_type')->where(['supplier_type_name'=>['in',$cate]])->column('supplier_type_name');
            $catearr = [];
            foreach ($cate as $cate_k=>$cate_v){
                if(!in_array($cate_v,$catelist)){
                    $catearr[] = $cate_v;
                }
            }
            //添加分类，如不填则返回错误
            if(!empty($catearr)){
                $this->error('分类不存在');
//                    foreach ($catedata as $cate_k=>$cate_v){
//                        if(strpos($cate_v,'/') !== false){
//                            $caterow = explode('/',$cate_v);
//                            foreach ($caterow as $caterow_k=>$caterow_v){
//                                if(in_array($caterow_v,$catearr) && !empty($caterow_v)){
//                                    $this->addGoodsCate($caterow);
//                                    break;
//                                }
//                            }
//                        }else{
//                            if(in_array($cate_v,$catearr) && !empty($cate_v)){
//                                $this->addGoodsCate([$cate_v]);
//                            }
//                        }
//                    }
            }
            $catelist = Db::name('kuyou_goods_type')->where(['supplier_type_name'=>['in',$cate]])->column('id','supplier_type_name');
            //计量单位
            $unitlist = Db::name('kuyou_unit')->where(['name'=>['in',$unit]])->column('name');
            $unitarr = [];
            $unitdata = [];
            foreach ($unit as $unit_k=>$unit_v){
                if(!in_array($unit_v,$unitlist)){
                    $unitarr[] = $unit_v;
                    $unitdata[] = [
                        'name'=>$unit_v,
                        'createtime'=>time(),
                        'updatetime'=>time(),
                    ];
                }
            }
            if(!empty($unitarr)){
                $this->error('计量单位不存在');
                Db::name('kuyou_unit')->insertAll($unitdata);
            }
            $unitlist = Db::name('kuyou_unit')->where(['name'=>['in',$unit]])->column('id','name');
            //处理多计量单位
            if(!empty($unit_con)){
                $conversion = [];
                foreach ($unit_con as $unit_con_k=>$unit_con_v){
                    $row = explode('/',$unit_con_v['unit']);
                    $advance_rate = explode('/',$unit_con_v['advance_rate']);
                    for ($a=0;$a<sizeof($row)-1;$a++){
                        $con = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$unitlist[$row[$a]],'vice_unit'=>$unitlist[$row[$a+1]],'advance_rate'=>((int)($advance_rate[$a+1]/$advance_rate[$a]))])->value('id');
                        if(!$con){
                            $conversion[] = [
                                'unit_name' => $row[$a].','.$row[$a+1].'(1:'.((int)($advance_rate[$a+1]/$advance_rate[$a])).')',
                                'main_unit' => $unitlist[$row[$a]],
                                'vice_unit' => $unitlist[$row[$a+1]],
                                'advance_rate' => ((int)($advance_rate[$a+1]/$advance_rate[$a])),
                                'createtime'=>time(),
                                'updatetime'=>time(),
                            ];
                        }
                    }
                }
            }
            if(!empty($conversion)){
                $this->error('多计量单位不存在');
//                    Db::name('kuyou_unit_conversion')->insertAll($conversion);
            }

            //仓库  不能新增，缺少仓库抛出
            $titles = array_filter($titles);
            foreach ($titles as $titles_k=>$titles_v){
                if(!in_array($titles_v,$stores) && $titles_v!='基础信息' && $titles_v!='价格管理'){
                    $stores[] = $titles_v;
                }
            }
            $storesarr = Db::name('kuyou_stores')->where(['name'=>['in',$stores]])->column('name');
            if(sizeof($storesarr)!=sizeof($stores)){
                foreach ($stores as $stores_k=>$stores_v){
                    if(!in_array($stores_v,$storesarr)){
                        $this->error($stores_v.'仓库不存在');
                    }
                }
            }
            $stores_list = Db::name('kuyou_stores')->where(['name'=>['in',$stores]])->column('id','name');

            $goodscode = Db::name('kuyou_goods')->where(['goods_code'=>['in',$goods_code]])->column('goods_code');
            $goodslist = Db::name('kuyou_goods')->where(['goods_code'=>['in',$goods_code]])->column('id','goods_code');//编号相同商品
            $params = [];
            $nowsp = '';
            $supplyer_code = [];
            foreach ($insert as $insert_k=>$insert_v){
                if(!empty($insert_v['商品编号'])){
                    $check = (new \app\api\model\kuyou\applet\Goods())::checkRow('',$insert_v['商品编号']);
                    if(isset($check['status']) && $check['status']>400){
                        $this->error($check['msg'].'，导入失败','',500);
                    }
                    $nowsp = $insert_k;
                    if(in_array($insert_v['商品编号'],$supplyer_code)){
                        $k = array_search($insert_v['商品编号'],$supplyer_code);
                        unset($params[$k]);
                    }
                    $supplyer_code[] = $insert_v['商品编号'];
                    $nowcate = explode('/',$insert_v['商品类别']);

                    $goods_price = [];

                    $unit = explode('/',$insert_v['计量单位']);
                    $market_sell_price = explode('/',$insert_v['零售价']);
                    $wholesale_price = explode('/',$insert_v['批发价']);
                    $vip_price = explode('/',$insert_v['会员价']);
                    $discount = explode('/',$insert_v['折扣率一']);
                    $discount2 = explode('/',$insert_v['折扣率二']);
                    $purchase = explode('/',$insert_v['预计采购价']);

                    foreach ($unit as $unit_k=>$unit_v){
                        $goods_price[] = [
                            'goods_code'        => $insert_v['商品编号'],
                            'goods_name'        => $insert_v['商品名称'],
                            'unit'              => $unitlist[$unit_v],
                            'market_sell_price' => $market_sell_price[$unit_k],
                            'wholesale_price'   => $wholesale_price[$unit_k],
                            'vip_price'         => $vip_price[$unit_k],
                            'discount'          => $discount[$unit_k],
                            'discount2'         => $discount2[$unit_k],
                            'purchase'          => $purchase[$unit_k],
                            'is_default'        => $unit_k<1?1:0,
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }

                    $inventory = 0;//总库存
                    $price = 0;
                    $stores_data = [];
                    $goods_stock_log = [];
                    foreach ($insert_v as $insert_v_k=>$insert_v_v){
                        if(strpos($insert_v_k,'期初数量') !== false){
                            $stores_name = explode('-',$insert_v_k);
                            $params[$insert_k]['period_status'] = 1;
                            $stores_data[] = [
                                'goods_code'   => $insert_v['商品编号'],
                                'attribute_id' => (!empty($insert_v['attr_arr'])?$insert_v['attr_arr']:null),
                                'stores_id' => $stores_list[$stores_name[1]],
                                'stock' => $insert_v_v,
                                'period' => $insert_v_v,
                                'unit_cost' => $insert_v['单位成本-'.$stores_name[1]],
                                'price' => round(($insert_v_v*$insert_v['单位成本-'.$stores_name[1]]),4),
                                'createtime' => time(),
                                'updatetime' => time(),
                            ];

                            $goods_stock_log[] = [
                                'business_type' => '1',
                                'goods_id'      => '',
                                'goods_code'    => $insert_v['商品编号'],
                                'attribute_id'  => (!empty($insert_v['attr_arr'])?$insert_v['attr_arr']:null),
                                'goods_unit'    => strpos($insert_v['计量单位'],'/') !== false?$unitlist[$unit[0]]:$unitlist[$insert_v['计量单位']],
                                'stores_id'     => $stores_list[$stores_name[1]],
                                'remark'        => $insert_v['备注'],
                                'balance_basics'=> (float)$insert_v_v,
                                'balance_unit'  => $insert_v_v>0?round(($insert_v_v*$insert_v['单位成本-'.$stores_name[1]])/$insert_v_v,4):0,
                                'balance_cost'  => round(($insert_v_v*$insert_v['单位成本-'.$stores_name[1]]),4),
                            ];

                            $inventory += $insert_v_v;
                            $price += round(($insert_v_v*$insert_v['单位成本-'.$stores_name[1]]),2);
                        }
                    }
                    $unit_cost = $inventory>0?round($price/$inventory,2):0;

                    $params[$insert_k] = [
                        'auxiliary'             => $insert_v['auxiliary'],
                        'auxiliary_type'        => $insert_v['auxiliary_type'],
                        'auxiliary_type_c'      => $insert_v['auxiliary_type_c'],
                        'goods_barcode'         => $insert_v['商品/属性条码'],

                        'goods_code'            => $insert_v['商品编号'],
                        'goods_name'            => $insert_v['商品名称'],
                        'goods_type_id'         => isset($catelist[$nowcate[sizeof($nowcate)-1]])?$catelist[$nowcate[sizeof($nowcate)-1]]:0,
                        'goods_specification_id'=> $insert_v['规格型号'],
                        'unit_id'               => strpos($insert_v['计量单位'],'/') !== false?$unitlist[$unit[0]]:$unitlist[$insert_v['计量单位']],
                        'note'                  => $insert_v['备注'],
                        'attribute_id'          => !empty($insert_v['attr_arr'])?$insert_v['attr_arr']:null,

                        'purchase'              => $goods_price[0]['purchase'],
                        'market_sell_price'     => $goods_price[0]['market_sell_price'],
                        'wholesale_price'       => $goods_price[0]['wholesale_price'],
                        'vip_price'             => $goods_price[0]['vip_price'],
                        'discount'              => $goods_price[0]['discount'],
                        'discount2'             => $goods_price[0]['discount2'],

                        'inventory'             => $inventory,
                        'period'                => $inventory,
                        'unit_cost'             => $unit_cost,
                        'price'                 => $price,

                        'createtime'            => time(),
                        'updatetime'            => time(),
                        'goods_price'          =>$goods_price,
                        'stores_data'          =>$stores_data,
                        'goods_stock_log'          =>$goods_stock_log
                    ];
                    foreach ($insert_v as $insert_v_k=>$insert_v_v){
                        if(strpos($insert_v_k,'期初数量') !== false){
                            $params[$insert_k]['period_status'] = 1;
                        }
                    }
                    if(strpos($insert_v['计量单位'],'/') !== false){
                        $params[$insert_k]['more_unit'] = 1;
                        $params[$insert_k]['more_unit_id'] = $unitlist[$unit[0]];
                    }else{
                        $params[$insert_k]['more_unit'] = 2;
                        $params[$insert_k]['more_unit_id'] = 0;
                    }

                    $row = $params[$nowsp]['goods_price'][0];
                    $row['attribute_id'] = $params[$nowsp]['attribute_id'];
                    unset($row['unit_id']);unset($row['is_default']);
                    $params[$nowsp]['attr_price'] = [];
                    $row['attr_code']         = isset($insert_v['属性编号'])?$insert_v['属性编号']:null;
                    if(!empty($row['attribute_id']) && !empty($row['attr_code'])){
                        $params[$nowsp]['attr_price'][] = $row;
                    }
                }else{
                    if(isset($params[$nowsp]['goods_price']) && !empty($insert_v['商品/属性条码'])){

                        if(!empty($insert_v['auxiliary_type_c'])){
                            $s = unserialize($insert_v['auxiliary_type_c']);
                            $auxiliary_type_c = unserialize($params[$nowsp]['auxiliary_type_c']);
                            foreach ($s as $k=>$v){
                                if(!empty($v) && !in_array($v,$auxiliary_type_c)){
                                    $auxiliary_type_c[] = $v;
                                    $params[$nowsp]['auxiliary_type_c'] = serialize($auxiliary_type_c);
                                }
                            }
                        }

                        if(strpos($insert[$nowsp]['计量单位'],'/') !== false){
                            $unit = explode('/',$insert[$nowsp]['计量单位']);
                            $market_sell_price = explode('/',$insert[$nowsp]['零售价']);
                            $wholesale_price = explode('/',$insert[$nowsp]['批发价']);
                            $vip_price = explode('/',$insert[$nowsp]['会员价']);
                            $discount = explode('/',$insert[$nowsp]['折扣率一']);
                            $discount2 = explode('/',$insert[$nowsp]['折扣率二']);
                            $purchase = explode('/',$insert[$nowsp]['预计采购价']);
                        }else{
                            $unit = explode('/',$insert[$nowsp]['计量单位']);
                            $market_sell_price = explode('/',$insert_v['零售价']);
                            $wholesale_price = explode('/',$insert_v['批发价']);
                            $vip_price = explode('/',$insert_v['会员价']);
                            $discount = explode('/',$insert_v['折扣率一']);
                            $discount2 = explode('/',$insert_v['折扣率二']);
                            $purchase = explode('/',$insert_v['预计采购价']);
                        }

                        $params[$nowsp]['attr_price'][] = [
                            'goods_code'        => $insert[$nowsp]['商品编号'],
                            'goods_name'        => $insert[$nowsp]['商品名称'],
                            'unit'              => (isset($params[$nowsp]['attr_price'][0]['unit'])?$params[$nowsp]['attr_price'][0]['unit']:0),
                            'market_sell_price' => $market_sell_price[0],
                            'wholesale_price'   => $wholesale_price[0],
                            'vip_price'         => $vip_price[0],
                            'discount'          => $discount[0],
                            'discount2'         => $discount2[0],
                            'purchase'          => $purchase[0],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                            'attribute_id'      => !empty($insert_v['attr_arr'])?$insert_v['attr_arr']:null,
                            'attr_code'         => isset($insert_v['属性编号'])?$insert_v['属性编号']:null,
                        ];

                        foreach ($insert_v as $insert_v_k=>$insert_v_v){
                            if(strpos($insert_v_k,'期初数量') !== false){
                                $stores_name = explode('-',$insert_v_k);
                                $params[$nowsp]['period_status'] = 1;
                                $params[$nowsp]['stores_data'][] = [
                                    'goods_code'        => $insert[$nowsp]['商品编号'],
                                    'attribute_id' => !empty($insert_v['attr_arr'])?$insert_v['attr_arr']:null,
                                    'stores_id' => $stores_list[$stores_name[1]],
                                    'stock' => $insert_v_v,
                                    'period' => $insert_v_v,
                                    'unit_cost' => $insert_v['单位成本-'.$stores_name[1]],
                                    'price' => round(($insert_v_v*$insert_v['单位成本-'.$stores_name[1]]),2),
                                    'createtime' => time(),
                                    'updatetime' => time(),
                                ];

                                $params[$nowsp]['goods_stock_log'][] = [
                                    'business_type' => '1',
                                    'goods_id'      => '',
                                    'goods_code'    => $insert_v['商品编号'],
                                    'attribute_id'  => (!empty($insert_v['attr_arr'])?$insert_v['attr_arr']:null),
                                    'goods_unit'    => (isset($params[$nowsp]['attr_price'][0]['unit'])?$params[$nowsp]['attr_price'][0]['unit']:0),
                                    'stores_id'     => $stores_list[$stores_name[1]],
                                    'remark'        => $insert_v['备注'],
                                    'balance_basics'=> (float)$insert_v_v,
                                    'balance_unit'  => $insert_v_v>0?round(($insert_v_v*$insert_v['单位成本-'.$stores_name[1]])/$insert_v_v,4):0,
                                    'balance_cost'  => round(($insert_v_v*$insert_v['单位成本-'.$stores_name[1]]),4),
                                ];
                            }
                        }
                    }
                }
            }
            $editstatus = isset($_POST['editstatus'])?$_POST['editstatus']:1;
            $update = [];
            $add_code = [];
            foreach ($params as $params_k=>$params_v){
                $inventory = 0;//总库存
                $price = 0;
                foreach ($params_v['stores_data'] as $k=>$v){
                    $inventory += $v['period'];
                    $price += $v['price'];
                }
                $unit_cost = $inventory>0?round($price/$inventory,2):0;
                $params[$params_k]['inventory'] = $inventory;
                $params[$params_k]['period'] = $inventory;
                $params[$params_k]['unit_cost'] = $unit_cost;
                $params[$params_k]['price'] = $price;
                //如果更新
                if($editstatus==1){
                    if(in_array($params_v['goods_code'],$goodscode)){
                        $params_v['id'] = $goodslist[$params_v['goods_code']];
                        $update[] = $params_v;
                        unset($params[$params_k]);
                    }else{
                        $add_code[] = $params_v['goods_code'];
                    }
                }else{
                    $add_code[] = $params_v['goods_code'];
                }
            }

            Db::startTrans();
            try {
                $where = [];
                $where['goods_code'] = ['in',$goods_code];
                Db::name('kuyou_goods_attr')->where($where)->delete();
                Db::name('kuyou_goods_batch')->where($where)->delete();
                Db::name('kuyou_goods_price')->where($where)->delete();
                Db::name('kuyou_goods_stock')->where($where)->delete();
                Db::name('kuyou_goods_period')->where($where)->delete();
                Db::name('kuyou_goods_log')->where($where)->delete();

                if(!empty($add_code)){
                    Db::name('kuyou_goods')->where(['goods_code'=>['in',$add_code]])->delete();
                }

                if(!empty($params)){
                    foreach ($params as $params_k=>$params_v){
                        $goods_price = $params_v['goods_price'];unset($params_v['goods_price']);
                        $stores_data = $params_v['stores_data'];unset($params_v['stores_data']);
                        $attr_price  = $params_v['attr_price'];unset($params_v['attr_price']);
                        $goods_stock_log  = $params_v['goods_stock_log'];unset($params_v['goods_stock_log']);
                        $result = Db::name('kuyou_goods')->insertGetId($params_v);

                        $attr = [];
                        if(!empty($attr_price)){
                            foreach ($attr_price as $data_k=>$data_v){
                                $attr_price[$data_k]['goods_id'] = $result;
                            }
                            foreach ($attr_price as $attr_price_k=>$attr_price_v){
                                $id = Db::name('kuyou_goods_attr')->insertGetId($attr_price_v);
                                $attr[$attr_price_v['attribute_id']] = $id;
                            }
                        }

                        if(!empty($goods_price)){
                            foreach ($goods_price as $data_k=>$data_v){
                                $goods_price[$data_k]['goods_id'] = $result;
                            }
                            Db::name('kuyou_goods_price')->insertAll($goods_price);
                        }
                        if(!empty($stores_data)){
                            foreach ($stores_data as $data_k=>$data_v){
                                $stores_data[$data_k]['goods_id'] = $result;
                                if(!empty($data_v['attribute_id'])){
                                    $attr_id = Db::name('kuyou_goods_attr')->where(['goods_code'=>$data_v['goods_code'],'attribute_id'=>$data_v['attribute_id']])->value('id');
                                    if(empty($attr_id)){
                                        exception('属性数据设置错误');
                                    }
                                    $stores_data[$data_k]['attribute_id'] = $attr_id;
                                }
                            }
                            Db::name('kuyou_goods_stock')->insertAll($stores_data);
                            Db::name('kuyou_goods_period')->insertAll($stores_data);
                        }
                        if(!empty($goods_stock_log)){
                            foreach ($goods_stock_log as $data_k=>$data_v){
                                $goods_stock_log[$data_k]['goods_id'] = $result;
                            }
                            Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
                        }
                    }
                }
                if(!empty($update)){
                    foreach ($update as $params_k=>$params_v){
                        $goods_price = $params_v['goods_price'];unset($params_v['goods_price']);unset($update[$params_k]['goods_price']);
                        $stores_data = $params_v['stores_data'];unset($params_v['stores_data']);unset($update[$params_k]['stores_data']);
                        $attr_price  = $params_v['attr_price'];unset($params_v['attr_price']);unset($update[$params_k]['attr_price']);
                        $goods_stock_log  = $params_v['goods_stock_log'];unset($params_v['goods_stock_log']);unset($update[$params_k]['goods_stock_log']);
                        if(!empty($goods_price)){
                            foreach ($goods_price as $data_k=>$data_v){
                                $goods_price[$data_k]['goods_id'] = $params_v['id'];
                            }
                            Db::name('kuyou_goods_price')->insertAll($goods_price);
                        }
                        if(!empty($stores_data)){
                            foreach ($stores_data as $data_k=>$data_v){
                                $stores_data[$data_k]['goods_id'] =$params_v['id'];
                            }
                            Db::name('kuyou_goods_stock')->insertAll($stores_data);
                            Db::name('kuyou_goods_period')->insertAll($stores_data);
                        }
                        if(!empty($attr_price)){
                            foreach ($attr_price as $data_k=>$data_v){
                                $attr_price[$data_k]['goods_id'] = $params_v['id'];
                            }
                            Db::name('kuyou_goods_attr')->insertAll($attr_price);
                        }
                        if(!empty($goods_stock_log)){
                            foreach ($goods_stock_log as $data_k=>$data_v){
                                $goods_stock_log[$data_k]['goods_id'] = $params_v['id'];
                            }
                            Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
                        }
                    }
                    if($editstatus==1 && !empty($update)){
                        $result = (new \app\api\model\kuyou\applet\Goods())->saveAll($update);
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($result){
                //导入成功删除文件
                $file = $this->request->post('file');
                $attachment = (new Attachment())->where(['url'=>$file])->find();
                if($attachment){
                    \think\Hook::add('upload_delete', function ($attachment) {
                        if ($attachment['storage'] == 'local') {
                            $attachmentFile = ROOT_PATH . '/public' . $attachment['url'];
                            if (is_file($attachmentFile)) {
                                @unlink($attachmentFile);
                            }
                        }
                    });
                    \think\Hook::listen("upload_delete", $attachment);
                    (new Attachment())->where(['url'=>$file])->delete();
                }
                $this->success('导入成功','',200);
            }else{
                $this->error('导入失败','',500);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取商品价格
     * @ApiMethod (POST)
     * @param int $data 信息数组
     */
    public function getgoodsinfo()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            foreach ($data as $k=>$v){
                $data[$k] = is_array($v)?$v:html_entity_decode($v);
            }
            $type = 1;
            if(isset($data['list'])){
                $data = (array)json_decode($data['list'],true);
                $type = 2;
            }
            if($type==1){
                $result = Goodss::getGoodsInfo($data);
            }else{
                $list = [];
                foreach ($data as $data_k=>$data_v){
                    $result = Goodss::getGoodsInfo($data_v);
                    if($result['status']!=500){
                        $list[] = $result['msg'];
                    }
                }
                $result['status'] = 200;
                $result['msg'] = $list;
            }
            if($result['status']==500){
                $this->error($result['msg'],'',$result['status']);
            }else{
                $this->success('查询成功',$result['msg'],200);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 选择商品
     * @ApiMethod (POST)
     * @param int $data 信息数组
     */
    public function choseGoods()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            foreach ($data as $k=>$v){
                $data[$k] = is_array($v)?$v:html_entity_decode($v);
            }
            $result = Goodss::choseGoods($data);
            if($result['status']==500){
                $this->error($result['msg'],'',$result['status']);
            }else{
                $this->success('查询成功',$result['msg'],200);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 选择商品
     * @ApiMethod (POST)
     * @param int $data 信息数组
     */
    public function getGoodsList()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            foreach ($data as $k=>$v){
                $data[$k] = is_array($v)?$v:html_entity_decode($v);
            }
            $result = Goodss::getGoodsList($data);
            if($result['status']==500){
                $this->error($result['msg'],'',$result['status']);
            }else{
                $this->success('查询成功',$result['msg'],200);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 商品价格格式化
     * @ApiMethod (POST)
     */
    public function formatInfo(){
        $data = input();

        if(isset($data['goods_attr'])){
            $data['attr'] = $data['goods_attr'];
        }
        $row = Db::name('kuyou_goods')->where(['goods_code'=>$data['goods_code']])->field('batch,serial,id,auxiliary,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id')->find();
        if(empty($row)){
            $this->error('未查询到商品数据','',250);
        }else{
            $goods_unit = $data['goods_unit'];
            if($row['more_unit']==1){//多单位，多属性以单位为准
                $goods_price = Db::name('kuyou_goods_price')->where(['goods_code'=>$data['goods_code'],'unit'=>$goods_unit])->find();
            }elseif ($row['more_unit']!=1 && $row['auxiliary']==1){//单一单位，多属性以属性价格为准
                $goods_price = Db::name('kuyou_goods_attr')->where(['id'=>$data['attr']])->find();
            }
        }

        //获取设置
        $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
        $setList = [];
        foreach ($set as $set_k=>$set_v){
            if(!empty($set_v['set'])){
                $set_v['set'] = unserialize($set_v['set']);
            }
            $setList[$set_v['name']] = $set_v;
        }
        //数量价格格式化
        $number_decimal = $setList['number_decimal']['value'];
        $price_decimal  = $setList['price_decimal']['value'];

        //税率
        if($data['tax_rate']===''){
            $suppliers = Db::name('kuyou_suppliers')->where(['supplyer_code'=>$data['supplyer_code']])->value('vat_rate');
            if(isset($suppliers) && $suppliers!==''){
                $data['tax_rate'] = $suppliers;
            }else{
                $data['tax_rate'] = $set['value'];
            }
        }

        //需格式化字段数组
        $format = [
            'number'=>$number_decimal,
            'allow_stock'=>$number_decimal,
            'basic_nmber'=>$number_decimal,
            'unit_price'=>$price_decimal,
            'tax_included'=>$price_decimal,
            'discount'=>$price_decimal,
            'dis_money'=>$price_decimal,
            'all_money'=>$price_decimal,
            'tax_rate'=>$price_decimal,
            'tax_money'=>$price_decimal,
            'money_tax_price'=>$price_decimal,
            'advance_rate'=>$number_decimal,
        ];
        foreach ($data as $k=>$v){
            if(array_key_exists($k,$format)){
                $data[$k] = (float)$data[$k];
            }
        }

        $taxes= Db::name('kuyou_sets')->where(['name'=>'price_taxes'])->value('is_checked');//价格含税
        $now_field = $data['now_field'];
        switch ($now_field){
            case 'goods_unit':
                //商品单位
                if($taxes){
                    $data['tax_included'] = isset($goods_price['purchase'])?$goods_price['purchase']:$data['tax_included'];//含税单价
                    $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                }else{
                    $data['unit_price'] = isset($goods_price['purchase'])?$goods_price['purchase']:$data['unit_price'];//单价
                    $data['tax_included'] = $data['unit_price']*(100+$data['tax_rate'])/100;//含税单价
                }
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100);//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'attr':
                //商品属性
                if($taxes){
                    $data['tax_included'] = isset($goods_price['purchase'])?$goods_price['purchase']:$data['tax_included'];//含税单价
                    $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                }else{
                    $data['unit_price'] = isset($goods_price['purchase'])?$goods_price['purchase']:$data['unit_price'];//单价
                    $data['tax_included'] = $data['unit_price']*(100+$data['tax_rate'])/100;//含税单价
                }
                $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100);//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'number':
                //数量
                $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100);//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'unit_price':
                //单价
                $data['tax_included'] = $data['unit_price']*(100+$data['tax_rate'])/100;//含税单价
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100);//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'tax_included':
                //含税单价
                $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100);//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'tax_rate':
                //税率
                $data['tax_included'] = $data['unit_price']*(100+$data['tax_rate'])/100;//含税单价
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100);//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'tax_money':
                //税额
                $data['money_tax_price'] = $data['all_money'] + $data['tax_money'];//价税合计减折扣额
                break;
            case 'discount':
                //折扣率
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100);//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'dis_money':
                //折扣额
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['discount'] = (100*$data['dis_money']+$data['dis_money']*$data['tax_rate'])/100;//折扣率
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100);//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'all_money':
                //购货金额
                $data['money_tax_price'] = $data['all_money']*(100+$data['tax_rate'])/100;//价税合计
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                $money_tax_price = $data['money_tax_price']*(100+$data['discount'])/100;//价税合计未减折扣额
                $data['tax_included'] = $money_tax_price/$data['number'];//含税单价
                $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                break;
            case 'money_tax_price':
                //价税合计
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                $money_tax_price = $data['money_tax_price']*(100+$data['discount'])/100;//价税合计未减折扣额
                $data['tax_included'] = $money_tax_price/$data['number'];//含税单价
                $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                break;
            default:
                //$this->error('格式化失败','now_field字段不能为空',500);
                break;
        }

        $data['advance_rate'] = 1;
        if($row['more_unit']==1){
            $advance_rate = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$row['more_unit_id'],'vice_unit'=>$goods_price['unit']])->value('advance_rate');
            if(!empty($advance_rate)){
                $data['advance_rate'] = $advance_rate;
            }
        }
        $data['basic_nmber'] = $data['number']*$data['advance_rate'];
        foreach ($data as $data_k=>$data_v){
            if(array_key_exists($data_k,$format)){
                $data[$data_k] = round($data[$data_k],$format[$data_k]);
            }
        }

        if(isset($data['tax_rate'])){
            $data['tax_money'] = $data['money_tax_price']-$data['all_money'];
        }else{
            $data['tax_money'] = 0;
        }

        $arr = [];
        foreach ($data as $data_k=>$data_v){
            if(array_key_exists($data_k,$format)){
                $data[$data_k] = round($data[$data_k],$format[$data_k]);
            }
            $arr[$data_k] = $data[$data_k];
        }
        $this->success('查询成功',$arr,200);
    }

    /**
     * 获取属性组合
     * @ApiMethod (POST)
     */
    public function auxiliary(){
        $post = $this->request->post();
        $list = $spec_name = Db::name('kuyou_auxiliary')->where(['id'=>['in',$post['type']]])->select();
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['spec'] = Db::name('kuyou_auxiliary')->where(['pid'=>$list_v['id'],'id'=>['in',$post['type_c']]])->column('name','id');
            $spec_name[$list_k]['spec'] = Db::name('kuyou_auxiliary')->where(['pid'=>$list_v['id'],'id'=>['in',$post['type_c']]])->column('id');
        }
        $lists = $this->combineDika($list);
        foreach ($lists as $lists_k=>$lists_v){
            $lists[$lists_k]['code'] = $post['code'].'_'.($lists_k+1);
            $lists[$lists_k]['spec_name'] = implode('/',$lists_v['spec']);
            $lists[$lists_k]['spec_id'] = $spec_id = explode('&',$lists_v['id']);
            $lists[$lists_k]['spec_arr'] = implode('/',$spec_id);
            foreach ($spec_id as $spec_id_k=>$spec_id_v){
                $lists[$lists_k]['spec_id'][$spec_id_k] =  $spec_id_v;
            }
        }
        $this->success('查询成功',['lists'=>$lists],200);
    }

    function combineDika(array $data) {
        $cnt = count($data);
        $result = $data[0];
        if($cnt==1){
            $list = [];
            foreach ($result['spec'] as $k=>$item) {
                $temp = [];
                $key = $k;
                $temp[] = $item;
                $list[] = ['id'=>$key,'spec'=>$temp];
            }
            return $list;
        }
        for($i = 1; $i < $cnt; $i++) {
            $result = $this->combineArray($result,$data[$i]);
        }
        return $result;
    }
    function combineArray($arr1,$arr2) {
        $result = array();
        if(!isset($arr1['spec'])){
            $arr1['spec'] = $arr1;
        }
        foreach ($arr1['spec'] as $k1=>$item1) {
            foreach ($arr2['spec'] as $k2=>$item2) {
                $temp = [];
                if(!isset($arr1['id'])){
                    $key = $item1['id'].'&'.$k2;
                }else{
                    $key = $k1.'&'.$k2;
                }
                if(is_array($item1)){
                    foreach ($item1['spec'] as $item1_k=>$item1_v){
                        $temp[] = $item1_v;
                    }
                }else{
                    $temp[] = $item1;
                }
                $temp[] = $item2;
                $result[] = ['id'=>$key,'spec'=>$temp];
            }
        }
        return $result;
    }

    /**
     * 获取单位成本
     * @ApiMethod (POST)
     */
    public function getCostPrice(){
        $post = $this->request->post();
        $goods_code = isset($post['goods_code'])?$post['goods_code']:'';
        $stores_id = isset($post['stores_id'])?$post['stores_id']:'';
        $supplyer_code = isset($post['supplyer_code'])?$post['supplyer_code']:'';
        $price = $this->getCost_Price($goods_code,$stores_id,$supplyer_code);
        $this->success('查询成功',['price'=>$price],200);
    }

    function getCost_Price($goods_code,$stores_id='',$supplyer_code=''){
        $price_decimal = \think\Db::name('kuyou_sets')->where(['name'=>'price_decimal'])->value('value');

        $valuation_set= \think\Db::name('kuyou_sets')->where(['name'=>'valuation'])->value('value');//计算方法
        $stores_set= \think\Db::name('kuyou_sets')->where(['name'=>'stores'])->value('is_checked');//是否分仓
        if($valuation_set!=2){
            $valuation_set = 1;
        }
        if($stores_set!=1){
            $stores_set = 0;
        }

        $taxe = \think\Db::name('kuyou_suppliers')->where(['supplyer_code'=>$supplyer_code])->value('vat_rate');
        if($taxe!==0){
            if(empty($taxe)){
                $taxe = \think\Db::name('kuyou_sets')->where(['name'=>'taxes'])->value('value');
            }
        }
        $set= \think\Db::name('kuyou_sets')->where(['name'=>'taxes'])->field('value,is_checked')->find();
        $price_taxes= \think\Db::name('kuyou_sets')->where(['name'=>'price_taxes'])->value('is_checked');

        $goods = \think\Db::name('kuyou_goods')->where(['goods_code'=>$goods_code])->find();
        //期初
        switch ($valuation_set){
            case 1:
                //移动平均法
                if($stores_set==1){
                    //期初
                    $goods_period = \think\Db::name('kuyou_goods_period')->where(['goods_code'=>$goods['goods_code'],'stores_id'=>$stores_id])->sum('period');
                    $goods_period_money = \think\Db::name('kuyou_goods_period')->where(['goods_code'=>$goods['goods_code'],'stores_id'=>$stores_id])->sum('price');

                    //成本调整
                    $adjustment_money = 0;
                    $adjustment = \think\Db::name('kuyou_adjustment_info')->where(['goods_id'=>$goods['id'],'stores_id'=>$stores_id])->select();
                    foreach ($adjustment as $adjustment_k=>$adjustment_v){
                        $advance_rate = 1;//单位换算进率
                        if($adjustment_v['goods_unit']!=$goods['unit_id']){
                            $unit = \think\Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$adjustment_v['goods_unit']])->value('advance_rate');
                            if(!empty($unit) && $unit>0){
                                $advance_rate = $unit;
                            }
                        }
                        $money = $adjustment_v['money']/$advance_rate;//换算后的调整成本
                        $adjustment_money += $money;
                    }
                    //成本调整结束
                    //采购
                    $where = [];
                    $where['goods_code'] = $goods['goods_code'];
                    $where['stores_id'] = $stores_id;
                    $basic_nmber = \think\Db::name('kuyou_goods_purchase_info')->where($where)->sum('basic_nmber');
                    $all_money = \think\Db::name('kuyou_goods_purchase_info')->where($where)->sum('all_money');

                    $chu = ($basic_nmber+$goods_period);
                    if($chu==0){
                        $cost = $goods['purchase'];
                        if($set['is_checked']==1){
                            if($price_taxes==1){
                                $cost = $cost*100/(100+$taxe);
                            }
                        }
                    }else{
                        $cost = ($goods_period_money+$all_money+$adjustment_money)/($basic_nmber+$goods_period);//成本
                    }
                }else{
                    $stores_ids = \think\Db::name('kuyou_stores')->where(['status'=>'1'])->column('id');
                    //期初
                    $goods_period = \think\Db::name('kuyou_goods_period')->where(['goods_code'=>$goods['goods_code'],'stores_id'=>['in',$stores_ids]])->sum('period');
                    $goods_period_money = \think\Db::name('kuyou_goods_period')->where(['goods_code'=>$goods['goods_code'],'stores_id'=>['in',$stores_ids]])->sum('price');

                    //成本调整
                    $adjustment_money = 0;
                    $adjustment = \think\Db::name('kuyou_adjustment_info')->where(['goods_id'=>$goods['id'],'stores_id'=>['in',$stores_ids]])->select();
                    foreach ($adjustment as $adjustment_k=>$adjustment_v){
                        $advance_rate = 1;//单位换算进率
                        if($adjustment_v['goods_unit']!=$goods['unit_id']){
                            $unit = \think\Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$adjustment_v['goods_unit']])->value('advance_rate');
                            if(!empty($unit) && $unit>0){
                                $advance_rate = $unit;
                            }
                        }
                        $money = $adjustment_v['money']/$advance_rate;//换算后的调整成本
                        $adjustment_money += $money;
                    }
                    //成本调整结束
                    //采购
                    $where = [];
                    $where['goods_code'] = $goods['goods_code'];
                    $where['stores_id'] = ['in',$stores_ids];
                    $basic_nmber = \think\Db::name('kuyou_goods_purchase_info')->where($where)->sum('basic_nmber');
                    $all_money = \think\Db::name('kuyou_goods_purchase_info')->where($where)->sum('all_money');

                    if(($basic_nmber+$goods_period)==0){
                        $cost = $goods['purchase'];
                        if($set['is_checked']==1){
                            if($price_taxes==1){
                                $cost = $cost*100/(100+$taxe);
                            }
                        }
                    }else{
                        $cost = ($goods_period_money+$all_money+$adjustment_money)/($basic_nmber+$goods_period);//成本
                    }
                }
                $cost = round($cost,$price_decimal);
                return $cost;
                break;
            case 2:
                //先进先出法
                $cost = $goods['purchase'];
                if($set['is_checked']==1){
                    if($price_taxes==1){
                        $cost = $cost*100/(100+$taxe);
                    }
                }
                $cost = round($cost,$price_decimal);
                return $cost;
                break;
            default:
                return '';
                break;
        }
    }

    /**
     * 获取商品价格
     * @ApiMethod (POST)
     * @param int $data 信息数组
     */
    public function getgoodsinfo_c()
    {
        if ($this->request->isPost()) {
            $keyword = $this->request->post('keyword');
            $goods = (new \app\api\model\kuyou\applet\Goods())->where(['goods_code|goods_barcode'=>['in',$keyword]])->select();
            $list = [];
            foreach ($goods as $goods_k=>$goods_v){
                $data = [];
                $data['id'] = $goods_v['id'];
                $data['goods_code'] = $goods_v['goods_code'];
                $data['store'] = $goods_v['warehousing'];
                $row = Goodss::getGoodsInfo($data);
                if($row['status']!=500){
                    $row['msg']['batch'] = $goods_v['batch'];
                    $row['msg']['serial'] = $goods_v['serial'];
                    $row['msg']['goods_type_id'] = $goods_v['goods_type_id'];
                    $list[] = $row['msg'];
                }
            }
            if(empty($list)){
                $this->error('查询失败','',500);
            }else{
                $this->success('查询成功',$list,200);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }
    
    /**
     * 获取上一次信息
     * @ApiMethod (POST)
     */
    public function getLastUser()
    {
        if ($this->request->isPost()) {
            $type = $this->request->post('type');
            $order_type = $this->request->post('order_type');
            switch ($type){
                case 1:
                    //供应商
                    $table = 'goods_purchase_order';
                    if($order_type==2){
                        $table = 'goods_purchase';
                    }
                    if($order_type==3){
                        $table = 'goods_exchange';
                    }
                    $code = Db::name('kuyou_'.$table)->order('id','DESC')->value('supplyer_code');
                    $user = Db::name('kuyou_suppliers')->where(['supplyer_code'=>$code])->find();
                    break;
                case 2:
                    //客户
                    $table = 'goods_sales_order';
                    if($order_type==2){
                        $table = 'goods_sales';
                    }
                    if($order_type==3){
                        $table = 'goods_sales_exchange';
                    }
                    $code = Db::name('kuyou_'.$table)->order('id','DESC')->value('customers_id');
                    $user = Db::name('kuyou_customers')->where(['id'=>$code])->find();
                    break;
                case 3:
                    //客户
                    $table = 'goods_sales_order';
                    if($order_type==2){
                        $table = 'goods_sales';
                    }
                    if($order_type==3){
                        $table = 'goods_sales_exchange';
                    }
                    $code = Db::name('kuyou_'.$table)->order('id','DESC')->value('sale_user');
                    $user = Db::name('kuyou_staff_member')->where(['id'=>$code])->find();
            }
            if(empty($user)){
                $this->error('未查询到相关信息','',500);
            }
            $this->success('查询成功',$user,200);
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    public function getGoods(){
        $data = input();
        if(isset($data['supplyer_code'])){
            $price_buy_last = Db::name('kuyou_sets')->where(['name'=>'price_buy_last'])->value('is_checked');
            if(empty($price_buy_last)){
                $this->error('未开启此设置','',500);
            }
            $s_type = $data['s_type'];
            switch ($s_type){
                case 1:
                    $table = 'kuyou_goods_purchase_order_info';
                    break;
                case 2:
                    $table = 'kuyou_goods_purchase_info';
                    break;
                case 3:
                    $table = 'kuyou_goods_exchange_info';
                    break;
                default:
                    $this->error('参数错误','',500);
            }
            $where = [];
            $where['supplyer_code'] = $data['supplyer_code'];
            $where['goods_code'] = $data['goods_code'];
            if(!empty($data['goods_attr'])){
                $where['goods_attr'] = $data['goods_attr'];
            }
            $price = Db::name($table)->where($where)->order(['purchase_time'=>'DESC','id'=>'DESC'])->field('unit_price,tax_included,createtime')->limit(5)->select();
            if(empty($price)){
                $this->error('未找到相关记录','',500);
            }else{
                $row = Db::name('kuyou_goods')->where(['goods_code'=>$data['goods_code']])
                    ->field('id,more_unit,unit_id,more_unit_id,purchase,market_sell_price,wholesale_price,vip_price,discount,discount2,auxiliary')->find();
                if($row['more_unit']!=1){
                    $unit_name = Db::name('kuyou_unit')->where(['id'=>$row['unit_id']])->value('name');
                    if($row['auxiliary']==1){
                        $where = [];
                        if($data['goods_attr']){
                            $where['id'] = $data['goods_attr'];
                        }
                        $goods_attr = Db::name('kuyou_goods_attr')->where($where)->where(['goods_id'=>$row['id']])
                            ->field('purchase,market_sell_price,wholesale_price,vip_price,discount,discount2')->find();
                        $row['purchase'] = isset($goods_attr['purchase'])?$goods_attr['purchase']:0;
                        $row['market_sell_price'] = isset($goods_attr['market_sell_price'])?$goods_attr['market_sell_price']:0;
                        $row['wholesale_price'] = isset($goods_attr['wholesale_price'])?$goods_attr['wholesale_price']:0;
                        $row['vip_price'] = isset($goods_attr['vip_price'])?$goods_attr['vip_price']:0;
                        $row['discount'] = isset($goods_attr['discount'])?$goods_attr['discount']:0;
                        $row['discount2'] = isset($goods_attr['discount2'])?$goods_attr['discount2']:0;
                    }
                    $goods_price = [
                        'unit' => $row['unit_id'],
                        'purchase' => $row['purchase'],
                        'market_sell_price' => $row['market_sell_price'],
                        'wholesale_price' => $row['wholesale_price'],
                        'vip_price' => $row['vip_price'],
                        'discount' => $row['discount'],
                        'discount2' => $row['discount2'],
                        'is_default' => 1,
                        'name' => $unit_name,
                    ];
                }else{
                    $goods_price = Db::name('kuyou_goods_price')->alias('g')
                        ->join('kuyou_unit u','u.id=g.unit')
                        ->where(['g.goods_id'=>$row['id'],'g.unit'=>$data['goods_unit']])
                        ->field('g.unit as unit_id,g.purchase,g.market_sell_price,g.wholesale_price,g.vip_price,g.discount,g.discount2,g.is_default,u.name')
                        ->find();
                }
                foreach ($price as $price_k=>$price_v){
                    $price[$price_k]['times'] = date('Y-m-d H:i:s',$price_v['createtime']);
                    $price[$price_k]['purchase'] = isset($goods_price['purchase'])?$goods_price['purchase']:'';
                }
                $this->success('查询成功',['price'=>$price],200);
            }
        }
        if(isset($data['customers_id'])){
            $price_buy_last = Db::name('kuyou_sets')->where(['name'=>'price_sale_last'])->value('is_checked');
            if(empty($price_buy_last)){
                $this->error('未开启此设置','',500);
            }
            $s_type = $data['s_type'];
            switch ($s_type){
                case 1:
                    $table = 'kuyou_goods_sales_order_info';
                    break;
                case 2:
                    $table = 'kuyou_goods_sales_info';
                    break;
                case 3:
                    $table = 'kuyou_goods_sales_exchange_info';
                    break;
                default:
                    $this->error('参数错误','',500);
            }
            $where = [];
            $where['customers_id'] = $data['customers_id'];
            $where['goods_code'] = $data['goods_code'];
            if(!empty($data['goods_attr'])){
                $where['goods_attr'] = $data['goods_attr'];
            }
            $price = Db::name($table)->where($where)->order(['purchase_time'=>'DESC','id'=>'DESC'])->field('unit_price,tax_included,createtime')->limit(5)->select();
            if(empty($price)){
                $this->error('未找到相关记录','',500);
            }else{
                $customerlevel = Db::name('kuyou_customers')
                    ->where(['id'=>$data['customers_id']])
                    ->value('customerlevel_id');
                $row = Db::name('kuyou_goods')->where(['goods_code'=>$data['goods_code']])
                    ->field('id,more_unit,unit_id,more_unit_id,purchase,market_sell_price,wholesale_price,vip_price,discount,discount2,auxiliary')->find();
                if($row['more_unit']!=1){
                    $unit_name = Db::name('kuyou_unit')->where(['id'=>$row['unit_id']])->value('name');
                    if($row['auxiliary']==1){
                        $where = [];
                        if($data['goods_attr']){
                            $where['id'] = $data['goods_attr'];
                        }
                        $goods_attr = Db::name('kuyou_goods_attr')->where($where)->where(['goods_id'=>$row['id']])
                            ->field('purchase,market_sell_price,wholesale_price,vip_price,discount,discount2')->find();
                        $row['purchase'] = isset($goods_attr['purchase'])?$goods_attr['purchase']:0;
                        $row['market_sell_price'] = isset($goods_attr['market_sell_price'])?$goods_attr['market_sell_price']:0;
                        $row['wholesale_price'] = isset($goods_attr['wholesale_price'])?$goods_attr['wholesale_price']:0;
                        $row['vip_price'] = isset($goods_attr['vip_price'])?$goods_attr['vip_price']:0;
                        $row['discount'] = isset($goods_attr['discount'])?$goods_attr['discount']:0;
                        $row['discount2'] = isset($goods_attr['discount2'])?$goods_attr['discount2']:0;
                    }
                    $goods_price = [
                        'unit' => $row['unit_id'],
                        'purchase' => $row['purchase'],
                        'market_sell_price' => $row['market_sell_price'],
                        'wholesale_price' => $row['wholesale_price'],
                        'vip_price' => $row['vip_price'],
                        'discount' => $row['discount'],
                        'discount2' => $row['discount2'],
                        'is_default' => 1,
                        'name' => $unit_name,
                    ];
                }else{
                    $goods_price = Db::name('kuyou_goods_price')->alias('g')
                        ->join('kuyou_unit u','u.id=g.unit')
                        ->where(['g.goods_id'=>$row['id'],'g.unit'=>$data['goods_unit']])
                        ->field('g.unit as unit_id,g.purchase,g.market_sell_price,g.wholesale_price,g.vip_price,g.discount,g.discount2,g.is_default,u.name')
                        ->find();
                }
                foreach ($price as $price_k=>$price_v){
                    $price[$price_k]['times'] = date('Y-m-d H:i:s',$price_v['createtime']);
                    switch ($customerlevel){
                        case 1:
                            $price[$price_k]['purchase'] = isset($goods_price['market_sell_price'])?$goods_price['market_sell_price']:'';
                            break;
                        case 2:
                            $price[$price_k]['purchase'] = isset($goods_price['wholesale_price'])?$goods_price['wholesale_price']:'';
                            break;
                        case 3:
                            $price[$price_k]['purchase'] = isset($goods_price['vip_price'])?$goods_price['vip_price']:'';
                            break;
                        case 4:
                            $price[$price_k]['purchase'] = isset($goods_price['market_sell_price'])?$goods_price['market_sell_price']*$goods_price['discount']/100:'';
                            break;
                        case 5:
                            $price[$price_k]['purchase'] = isset($goods_price['market_sell_price'])?$goods_price['market_sell_price']*$goods_price['discount2']/100:'';
                            break;
                        default:
                            $price[$price_k]['purchase'] = isset($goods_price['market_sell_price'])?$goods_price['market_sell_price']:'';
                    }
                }
                $this->success('查询成功',['price'=>$price],200);
            }
        }
        $this->error('参数错误','',500);
    }
}
